package com.ailiwu.www.ailiwu.Fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.ailiwu.www.ailiwu.R;
import com.ailiwu.www.ailiwu.adapter.MyRecyclerViewAdapter;
import com.ailiwu.www.ailiwu.base.BaseFragment;
import com.ailiwu.www.ailiwu.bean.ItemBean;
import com.ailiwu.www.ailiwu.url.Urls;
import com.ailiwu.www.ailiwu.utils.Logger;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.melnykov.fab.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:    XiYoung
 * Version    V1.0
 * Date:      2015/12/4 000415:49
 * Description:
 * Modification  History:
 * Date         	Author        		Version        	Description
 * -----------------------------------------------------------------------------------
 * 2015/12/4 0004       XiYoung              1.0                   1.0
 * Why & What is modified:
 */
public class BaseHomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    private ArrayList<ItemBean.DataEntity.ItemsEntity> itemsEntities = new ArrayList<>();
    private static final String CHANNEL_ID = "channel";
    private static final String ARG_NAME = "args";
    private String mChannelName;
    private String next_url;
    private int mChannelId;
    private RecyclerView mRecyclerView;
    private MyRecyclerViewAdapter myRecyclerViewAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;//下拉刷新空间
    private boolean isReflash = false;

    public BaseHomeFragment() {

    }

    public static BaseHomeFragment newInstance(String arg, int channelId) {
        BaseHomeFragment fragment = new BaseHomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_NAME, arg);
        args.putInt(CHANNEL_ID, channelId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mChannelName = getArguments().getString(ARG_NAME);
            mChannelId = getArguments().getInt(CHANNEL_ID);
        }
    }

    @Override
    protected View inflateView() {
        return View.inflate(mAcAvtivity, R.layout.fragment_home_second, null);
    }

    @Override
    protected void initView(View view) {
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.mainColor);
        mSwipeRefreshLayout.setOnRefreshListener(this);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recy_home_second);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mAcAvtivity);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        myRecyclerViewAdapter = new MyRecyclerViewAdapter(mAcAvtivity, itemsEntities);
        mRecyclerView.setAdapter(myRecyclerViewAdapter);
        FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
        fab.attachToRecyclerView(mRecyclerView);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linearLayoutManager.smoothScrollToPosition(mRecyclerView, null, 0);
            }
        });


        mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                int itemCount = linearLayoutManager.getItemCount();
                if (lastVisibleItemPosition + 1 == itemCount) {
                    //加载下一页内容
                    if (!isReflash) {
                        updataRecycler(next_url);
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        updataRecycler(Urls.homeTabUrl(mChannelId));
    }

    private void updataRecycler(String url) {
        if (url != null) {
            isReflash = true;
            httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    String result = responseInfo.result;
                    //TODO 存入数据库
                    if (result != null) {
                        Logger.i(result);
                        ItemBean itemBean = gson.fromJson(result, ItemBean.class);
                        List<ItemBean.DataEntity.ItemsEntity> items = itemBean.getData().getItems();
                        itemsEntities.addAll(items);
                        myRecyclerViewAdapter.notifyDataSetChanged();
                        next_url = itemBean.getData().getPaging().getNext_url();
                        isReflash = false;
                    }
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    // TODO: 2015/12/3 0003 网络连接失败
                    Snackbar.make(mRecyclerView, "哎呀！网络连接失败了！！", Snackbar.LENGTH_LONG).show();
                }

            });
        }
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (mSwipeRefreshLayout.isRefreshing()) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        }, 2000);
    }
}
